package org.examples.simplemulti;

import lombok.extern.slf4j.Slf4j;

import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
import org.apache.hc.core5.io.CloseMode;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.Future;

import static org.examples.DebugConstants.*;

@Slf4j
public class AsyncBytesWrapper {
  public static void main(final String[] args) throws Exception {
    final HttpEntity reqEntity = MultipartEntityBuilder.create()
        .addPart("name1", new StringBody("{\"k1\":\"v1\"}", ContentType.APPLICATION_JSON))
        .addPart("name2", new StringBody("{\"k2\":\"v2\"}", ContentType.APPLICATION_JSON))
        .build();
    String contentType = reqEntity.getContentType();

    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    client.start();
    final HttpHost target = new HttpHost("httpbin.org");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    reqEntity.writeTo(baos);
    byte[] bytes = baos.toByteArray();
    BasicAsyncEntityProducer multiPartProducer = new BasicAsyncEntityProducer(
        bytes,
        ContentType.MULTIPART_FORM_DATA
    );
    final SimpleHttpRequest request = SimpleRequestBuilder
        .post()
        .setHttpHost(target)
        .setScheme("https")
        .setPath("/post")
        .setHeader("Content-Type", contentType)
        .build();

    final Future<SimpleHttpResponse> future = client.execute(
        new BasicRequestProducer(request,
            multiPartProducer
        ),
        SimpleResponseConsumer.create(), null);
    SimpleHttpResponse resp = future.get();
    System.out.println(resp.getBodyText());
    client.close(CloseMode.GRACEFUL);
  }
}
